package com.colabo.j2ee.web.oaf.security.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.dao.DataAccessException;

import com.colabo.j2ee.web.core.common.CommonConstants;
import com.colabo.j2ee.web.core.exception.ReadableMessage;
import com.colabo.j2ee.web.core.exception.ServiceException;
import com.colabo.j2ee.web.core.persistence.HqlWrapper;
import com.colabo.j2ee.web.core.pkgenerator.IPKGenerator;
import com.colabo.j2ee.web.core.service.impl.DefaultServiceImpl;
import com.colabo.j2ee.web.core.util.StringUtil;
import com.colabo.j2ee.web.oaf.common.AppConstants;
import com.colabo.j2ee.web.oaf.orgnization.model.IPRoleVO;
import com.colabo.j2ee.web.oaf.orgnization.model.SCUnitProfileVO;
import com.colabo.j2ee.web.oaf.security.IRoleMaintainService;

/**
 * 角色授权业务操作Hibernate实现
 */
public class RoleMaintainImpl extends DefaultServiceImpl implements IRoleMaintainService {
	private IPKGenerator keyService = null;
	public Object[] initData(int aPageSize) throws ServiceException {
		String sql = "from IPRoleVO where delFlag = 'n' ";
		Object[] result = this.find_Hibernate_ComposedHQL(sql, null, null, null, 0, aPageSize, true, null, null, null);
		return result;
	}

	public String saveData(Map aObjectList) throws ServiceException {
		try {
			// 插入成功的记录数、更新成功的记录数、删除成功的记录数
			int insertCount = 0;
			int updateCount = 0;
			int deleteCount = 0;

			// 删除主键列表、更新bean的列表、新增bean的列表
			List deleteBeanList = (ArrayList) aObjectList.get(CommonConstants.DELETE_BEAN_LIST);
			List insertBeanList = (ArrayList) aObjectList.get(CommonConstants.INSERT_BEAN_LIST);
			List updateBeanList = (ArrayList) aObjectList.get(CommonConstants.UPDATE_BEAN_LIST);

			IPRoleVO bean;

			// 批量插入记录
			if (insertBeanList.size() > 0) {
				for (int i = 0; i < insertBeanList.size(); i++) {
					bean = (IPRoleVO) insertBeanList.get(i);

					List list = this.findAll_Hibernate_ComposedHQL("from IPRoleVO where roleName='"
							+ bean.getRoleName() + "'");
					if (list != null && list.size() > 0) {
						IPRoleVO vo = (IPRoleVO) list.get(0);
						if ("y".equals(vo.getDelFlag())) {// 如果存在已删除同名的角色，则将其恢复为未删除状态
							bean.setStatus("1");
							bean.setDelFlag("n");
							bean.setRoleid(vo.getRoleid());
							this.update_Hibernate_Object(bean);
							insertPosition(bean.getId(), bean.getRoleName());
						} else {// 如果存在未删除同名的角色，返回角色信息
							return "1" + vo.getRoleName();
						}
					} else {
						bean.setRoleid(keyService.getUUIDKey());
						bean.setStatus("1");
						bean.setDelFlag("n");
						this.save_Hibernate_Object(bean);
						insertCount++;
						insertPosition(bean.getId(), bean.getRoleName());
					}
				}
			}

			// 批量更新记录
			if (updateBeanList.size() > 0) {
				for (int i = 0; i < updateBeanList.size(); i++) {
					bean = (IPRoleVO) updateBeanList.get(i);
					String id = bean.getId();
					List list = this.findAll_Hibernate_ComposedHQL("from IPRoleVO where roleName='"
							+ bean.getRoleName() + "' and roleid<>'"+id+"'");
					if (list != null && list.size() > 0) {
						IPRoleVO vo = (IPRoleVO) list.get(0);
						if ("y".equals(vo.getDelFlag())) {// 如果存在已删除同名的角色，则将其恢复为未删除状态
							return "2" + vo.getRoleName();
						} else {// 如果存在未删除同名的角色，返回角色信息

							return "1" + vo.getRoleName();
						}
					} else {
						IPRoleVO vo = (IPRoleVO)this.findByID_Hibernate_Get(IPRoleVO.class, id);
						String name = vo.getRoleName();
						this.update_Hibernate_Object(bean);
						updateCount++;
						updatePosition(id, bean.getRoleName());
						updateConnctionPosition(id, name, bean.getRoleName());
					}
				}
			}

			// 批量删除记录
			if (deleteBeanList.size() > 0) {
				for (int i = 0; i < deleteBeanList.size(); i++) {
					bean = (IPRoleVO) deleteBeanList.get(i);
					bean.setDelFlag("y");
					this.update_Hibernate_Object(bean);
					deleteCount++;
					deletePostion(bean.getId(), bean.getRoleName());
					deleteRoleUnitRel(bean.getId());
				}
			}
			return "0";
		} catch (DataAccessException dae) {
			ReadableMessage msg = new ReadableMessage(AppConstants.MSG_ERR_APP_5005);
			throw new ServiceException(msg, dae);
		}
	}

	private void insertPosition(String roleId, String name) throws ServiceException {
		String sql = "";
		sql = "insert into wf_position (POSITIONID, UNITID, ROLEID, KIND, POSITIONNAME)" + " values ('"
				+ keyService.getUUIDKey() + "', '" + AppConstants.VIRTUAL_UNIT_ID + "', " + "'" + roleId
				+ "', '1','" + name.replaceAll("'", "''") + "')";
		getJdbcTemplate().execute(sql);
	}

	private void updatePosition(String roleId, String name) throws ServiceException {
		String sql = "update wf_position set POSITIONNAME='" + name.replaceAll("'", "''") + "' where UNITID='"
				+ AppConstants.VIRTUAL_UNIT_ID + "' and " + " ROLEID='" + roleId + "'";
		getJdbcTemplate().execute(sql);
	}
	
	private void updateConnctionPosition(String roleId, String oldname, String newname) throws ServiceException {
		String sql = "UPDATE WF_POSITION SET POSITIONNAME=REPLACE(POSITIONNAME,'" + oldname.replaceAll("'", "''")
				+"','"+newname.replaceAll("'", "''") 
				+ "') WHERE POSITIONID IN (SELECT POSITIONID FROM IP_ROLE_UNIT_REL WHERE "
				+ " ROLEID='" + roleId + "')";
		getJdbcTemplate().execute(sql);
	}

	private void deletePostion(String roleId, String name) throws ServiceException {
		String sql = "delete from wf_position " + " where ROLEID='" + roleId + "'";
		getJdbcTemplate().execute(sql);
	}
	
	private void deleteRoleUnitRel(String roleId) throws ServiceException {
		String sql = "DELETE FROM IP_ROLE_UNIT_REL " + " WHERE ROLEID='" + roleId + "'";
		getJdbcTemplate().execute(sql);
	}

	public Object[] queryData(Map aParams, int aOffset, int aPageSize) throws ServiceException {
		String sql = "from IPRoleVO";
		// 筛选参数，将空参数除去
		HqlWrapper wrapper = new HqlWrapper();
		wrapper.setCondition("rolename", HqlWrapper.INCLUDE, aParams.get("rolename"));
		wrapper.setCondition("delFlag", HqlWrapper.EQUAL, "n");
		String[] propertyNames = StringUtil.listToStrArray(wrapper.getPropertyNames());
		String[] operators = StringUtil.listToStrArray(wrapper.getOperators());

		List valuesList = wrapper.getValues();
		Object[] values = valuesList == null || valuesList.size() == 0 ? null : valuesList.toArray();
		String orderBy = null;
		String groupBy = null;
		String otherCause = null;
		Object[] result = this.find_Hibernate_ComposedHQL(sql, propertyNames, operators, values, aOffset, aPageSize,
				true, orderBy, groupBy, otherCause);
		return result;
	}

	public Object[] reloadData(Map aParams, int aOffset, int aPageSize) throws ServiceException {
		return null;
	}

	public IPKGenerator getKeyService() {
		return keyService;
	}

	public void setKeyService(IPKGenerator keyService) {
		this.keyService = keyService;
	}

	public void saveRolePosition(String roles, String units) throws ServiceException {
		String[] rl = roles.split(",");
		String[] ul = units.split(",");

		String sql = "insert into wf_position (POSITIONID,POSITIONCODE,UNITID, ROLEID, KIND,TYPE, POSITIONNAME)"
				+ "values(?,?,?,?,'1','C',?)";
		
		String relsql = "INSERT INTO IP_ROLE_UNIT_REL (relky,POSITIONID,UNITID, ROLEID)"
			+ "VALUES(?,?,?,?)";
		int rCount = rl.length;
		int uCount = ul.length;

		Connection conn = null;
		PreparedStatement ps = null;
		PreparedStatement relps = null;

		int count = 0;
		try {
			conn = getJdbcTemplate().getDataSource().getConnection();
			ps = conn.prepareStatement(sql);
			relps = conn.prepareStatement(relsql);

			IPRoleVO ro = null;
			SCUnitProfileVO uo = null;
			String rId = "";
			String uId = "";
			String tmpId = "";
			String reltmpId = "";
			Map tmp = new HashMap();
			for (int i = 0; i < rCount; i++) {
				rId = rl[i];
				if (rId == null || rId.length() < 1) {
					continue;
				}
				ro = (IPRoleVO) findByID_Hibernate_Get(IPRoleVO.class, rId);
				for (int j = 0; j < uCount; j++) {
					uId = ul[j];
					if (uId == null || uId.length() < 1) {
						continue;
					}
					if (tmp.containsKey(uId)) {
						uo = (SCUnitProfileVO) tmp.get(uId);
					} else {
						uo = (SCUnitProfileVO) findByID_Hibernate_Get(SCUnitProfileVO.class, uId);
						if (uo != null) {
							tmp.put(uId, uo);
						}
					}

					if (isExist(conn, uId, rId)) {
						continue;
					}
					tmpId = keyService.getUUIDKey();
					ps.setString(1, tmpId);
					ps.setString(2, tmpId);
					ps.setString(3, uId);
					ps.setString(4, rId);
					ps.setString(5, uo.getUnitName() + ro.getRoleName());
					ps.addBatch();
					
					reltmpId = keyService.getUUIDKey();
					relps.setString(1, reltmpId);
					relps.setString(2, tmpId);
					relps.setString(3, uId);
					relps.setString(4, rId);
					relps.addBatch();
					
					count++;
					if (count > 50) {
						ps.executeBatch();
						ps.clearBatch();
						
						relps.executeBatch();
						relps.clearBatch();
						
						count = 0;
					}
				}
			}
			ps.executeBatch();
			relps.executeBatch();
			// conn.commit();

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if(relps != null){
					relps.close();
				}
				
				if(ps != null){
					ps.close();
				}
				
				if(conn != null){
					conn.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	private boolean isExist(Connection conn, String unit, String role) throws SQLException {
		boolean rv = false;
		try {
			Statement st = conn.createStatement();
			ResultSet rs = st.executeQuery("SELECT POSITIONID FROM " + "IP_ROLE_UNIT_REL WHERE UNITID='" + unit
					+ "' AND ROLEID='" + role + "'");
			if (rs.next()) {
				rv = true;
			}
			rs.close();
			st.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return rv;
	}
}
